package com.yangkunhong.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yangkunhong.constant.ErrMsg;
import com.yangkunhong.pojo.PageDataResponse;
import com.yangkunhong.pojo.ResponseData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.Map;

/**
 * ClassName: ServletUtil
 * Description:
 *
 * @author yangkunhong
 * @date 2024/6/27 10:19
 */
public class AjaxUtils {

    /**
     * 判断请求是否可能是AJAX请求
     *
     * @param request HTTP请求对象
     * @return 如果是AJAX请求返回true，否则返回false
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equalsIgnoreCase(requestedWith);
    }
    public static Map<String, String> parseJsonToMap(HttpServletRequest req) throws IOException {

        //1 接收参数
        String json = JSONUtils.parseJsonInputStream(req);
        //2 解析数据
        Gson gson = new Gson();
        Type mapType = new TypeToken<Map<String, String>>() {}.getType();
        return gson.fromJson(json, mapType);


    }
    public static <T>T parseJsonToVo(HttpServletRequest req,Class<T> vo) throws IOException {
        //1 接收参数
        String json = JSONUtils.parseJsonInputStream(req);
        //2 解析数据
        Gson gson = new Gson();
        return gson.fromJson(json, vo);

    }
    public static <T> T convertRequestToBean(HttpServletRequest request, Class<T> clazz) {
        T bean = null;
        try {
            bean = clazz.getDeclaredConstructor().newInstance();
            // 假设有一个无参构造函数
            Enumeration<String> paramNames = request.getParameterNames();

            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                String paramValue = request.getParameter(paramName);

                // 使用反射设置bean的字段值
                Field field = clazz.getDeclaredField(paramName);
                field.setAccessible(true);
                // 设置为可访问，以便可以访问私有字段
                // 这里只处理了String类型的字段，对于其他类型，你可能需要添加额外的逻辑

                if (field.getType() == String.class) {
                    field.set(bean, paramValue);
                }else if (field.getType() == int.class) {
                    // 使用Integer.parseInt来转换字符串到int
                    // 注意这里要处理NumberFormatException异常
                    try {
                        // int intValue = Integer.parseInt(paramValue);

                        field.setInt(bean, Integer.valueOf(paramValue));
                    } catch (NumberFormatException e) {
                        // 你可以选择抛出异常、记录错误或设置默认值
                        // 这里仅作为示例，我们设置字段为0
                        field.setInt(bean, Integer.valueOf(0));
                    }
                }else if (field.getType() == Integer.class) {
                    // 使用Integer.parseInt来转换字符串到int
                    // 注意这里要处理NumberFormatException异常
                    try {
                       // int intValue = Integer.parseInt(paramValue);

                        field.set(bean, Integer.valueOf(paramValue));
                    } catch (NumberFormatException e) {
                        // 你可以选择抛出异常、记录错误或设置默认值
                        // 这里仅作为示例，我们设置字段为0
                        field.set(bean, Integer.valueOf(0));
                    }
                }else if(field.getType() == BigDecimal.class){
                    try {
                        field.set(bean, new BigDecimal(paramValue));
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        // 你可以选择抛出异常、记录错误或设置默认值
                        // 这里仅作为示例，我们设置字段为0
                        field.set(bean, new BigDecimal("0"));
                    }
                } else if (field.getType() == long.class) {
                    // 使用Long.parseLong来转换字符串到long
                    try {
                        long longValue = Long.parseLong(paramValue);
                        field.setLong(bean, longValue);
                    } catch (NumberFormatException e) {
                        // 你可以选择抛出异常、记录错误或设置默认值
                        // 这里仅作为示例，我们设置字段为0
                        field.setLong(bean, 0L);
                    }
                }else{
                    System.out.println("paramName=" + paramName);
                    System.out.println("paramValue=" + paramValue);
                }
                // ... 可以添加对其他类型的处理逻辑
            }
        } catch (Exception e) {
            e.printStackTrace(); // 实际开发中应该使用更合适的错误处理机制
        }
        return bean;
    }
    public static String parseJsonInputStream(HttpServletRequest req) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = req.getInputStream();
            if (inputStream != null) {
                // 指定字符编码为UTF-8
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    // 通常在这里不会重新抛出异常，而是记录日志或采取其他恢复措施
                    // throw ex; // 不建议在这里重新抛出异常，因为它会覆盖原始的IOException
                }
            }
        }
        return stringBuilder.toString();
    }

    public static void sendJsonResponse(ErrMsg errMsg, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        ResponseData responseData = new ResponseData();
        responseData.setCode(errMsg.getCode());
        responseData.setMessage(errMsg.getMessage());
        resp.getWriter().print((new Gson()).toJson(responseData));
        resp.getWriter().close();

    }

    public static void sendJsonResponse(PageDataResponse pageDataResponse, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print((new Gson()).toJson(pageDataResponse));
        resp.getWriter().close();

    }
}
